const $ID = ID => document.querySelector('#' + ID);
const $STY = sty => document.querySelector('.' + sty);

const formatDate = date => date.toLocaleString('zh-Hans-CN', {
    hour12: false,
    month: 'numeric',
    day: 'numeric',
    hour: 'numeric',
    minute: 'numeric',
    second: 'numeric'
})

const getJson = async (url, callback) => {
    try {
        let rsp = await fetch(url, {
            method: 'GET',
            headers: { 'content-type': 'application/json' }
        });

        let rst = await rsp.json();

        typeof callback === "function" && callback(rst);

    } catch (err) {
        console.error(err);
        typeof callback === "function" && callback(err);
    }
};

const delAsk = async (url, callback) => {
    try {
        await fetch(url, { method: 'DELETE' });

        let rst = await rsp.json();

        typeof callback === "function" && callback(rst);

    } catch (err) {
        console.error(err)
        typeof callback === "function" && callback(err);
    }
};

const putData = async (url, params, callback) => {
    try {
        let rsp = await fetch(url, {
            method: 'PUT',
            headers: { 'Content-type': 'application/json' },
            body: JSON.stringify(params)
        });

        let rst = await rsp.json();

        typeof callback === "function" && callback(rst);

    } catch (err) {
        console.error(err);
        typeof callback === "function" && callback(err);
    }
}

const patchData = async (url, params, callback) => {
    try {
        let rsp = await fetch(url, {
            method: 'PATCH',
            headers: { 'Content-type': 'application/json' },
            body: JSON.stringify(params)
        });

        let rst = await rsp.json();

        typeof callback === "function" && callback(rst);

    } catch (err) {
        console.error(err);
        typeof callback === "function" && callback(err);
    }
}

const postData = async (url, params, callback) => {
    try {
        let rsp = await fetch(url, {
            method: 'POST',
            headers: { 'Content-type': 'application/json' },
            body: JSON.stringify(params)
        });

        let rst = await rsp.json();

        typeof callback === "function" && callback(rst);

    } catch (err) {
        console.error(err);
        typeof callback === "function" && callback(err);
    }
}

const getSSItem = key => JSON.parse(sessionStorage.getItem(key));
const setSSItem = (key, obj) => sessionStorage.setItem(key, JSON.stringify(obj));
